import NumberUtil from "@/NumberUtil";
import ActorTypeUtil from "@/ActorTypeUtil";

/**
 * 演员id等表格id 通常为方便人记忆的中文长字符
 * 存档时可以使用此工具映射短id以节省存储
 */

/** @noSelf **/
export default class ShortIDUtil {

    static shortIdFullIdMap: { [shortId: string]: string } = {};
    static fullIdShortIdMap: { [full_id: string]: string } = {};

    /**
     * 初始化所有演员的短id
     */
    static initAllActorTypeShortIDs() {
        ActorTypeUtil.forAllActorTypes(actorType => {
            let shortId = actorType.shortId;
            if (actorType.shortIdindex) {
                shortId = ShortIDUtil.calculateShortIdByIndexNumber(actorType.shortIdindex)
            }
            if (shortId == null) {
                shortId = ShortIDUtil.calculateShortId(actorType.id)
            }
            ShortIDUtil.setFullIdAndShortIdMap(actorType.id, shortId);
        });
        ActorTypeUtil.addRegisterActorTypeListener(actorType => {
            let shortId = actorType.shortId;
            if (actorType.shortIdindex) {
                shortId = ShortIDUtil.calculateShortIdByIndexNumber(actorType.shortIdindex)
            }
            if (shortId == null) {
                shortId = ShortIDUtil.calculateShortId(actorType.id)
            }
            ShortIDUtil.setFullIdAndShortIdMap(actorType.id, shortId);
        })
    }


    /**
     * 计算 完整id 的 id哈希短编码
     * @param full_id
     */
    static calculateShortId(full_id: string) {
        let stringHash = Math.abs(StringHash(full_id));
        return NumberUtil.toUnsignedString(stringHash, 74);
    }

    /**
     * 计算 完整id 的 短id
     * @param indexNumber 这个在类别里是唯一的
     * @param kind 可使用a-z A-Z 单字母 或更长字符
     */
    static calculateShortIdByIndexNumber(indexNumber: number, kind?: string): string {
        let ijz = NumberUtil.toUnsignedString(indexNumber, 86);
        if (kind) {
            return kind + ":" + ijz;
        }
        return ijz;
    }

    /**
     * 设置 完整id 与 id短编码 映射关系
     * @param full_id
     * @param shortId
     */
    static setFullIdAndShortIdMap(full_id: string, shortId: string): void {
        if (ShortIDUtil.shortIdFullIdMap[shortId]) {
            log.errorWithTraceBack("fullId2shortId映射冲突:[" + ShortIDUtil.shortIdFullIdMap[shortId] + "]和[" + full_id + "]都映射到短id:" + shortId);
            return;
        }
        ShortIDUtil.fullIdShortIdMap[full_id] = shortId;
        ShortIDUtil.shortIdFullIdMap[shortId] = full_id;
    }

    /**
     * 完整id转 id短编码 如果之前没有映射短id则返回传入参数
     * @param full_id
     */
    static fullId2shortId(full_id: string): string {
        if (full_id == null) {
            return null;
        }
        return ShortIDUtil.fullIdShortIdMap[full_id] || full_id;
    }

    /**
     * id短编码 转完整的id 如果之前没有映射短id则返回传入参数
     * @param shortId
     */
    static shortId2fullId(shortId: string): string {
        if (shortId == null) {
            return null;
        }
        return ShortIDUtil.shortIdFullIdMap[shortId] || shortId;
    }


}